package com.googlecode.rjm.model.custom;

import java.text.ParseException;
import java.util.Date;

import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.ForceDiscriminator;

import com.googlecode.rjm.model.Persistent;
import com.googlecode.rjm.util.DateUtil;

@Entity
@Table(name = "custom_values")
@DiscriminatorColumn(name = "customized_type")
@ForceDiscriminator
public abstract class CustomValue<T> extends Persistent {

	private static final long serialVersionUID = 1L;

	@Id
	private Integer id;

	@ManyToOne
	@JoinColumn(name = "custom_field_id")
	@Fetch(FetchMode.SELECT)
	private CustomField field;

	private String value;

	@Override
	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public CustomField getField() {
		return this.field;
	}

	public void setField(CustomField field) {
		this.field = field;
	}

	public String getValue() {
		return this.value;
	}

	public void setValue(String value) {
		this.value = value;
	}
	
	/**
	 * @return Value parsed as {@linkplain Date}, null if the format is invalid.
	 */
	public Date getValueAsDate() {
		try {
			return DateUtil.format.parse(getValue());
		} catch (ParseException e) {
			return null;
		}
	}

}
